package com.ruoyi.mymod.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mymod.service.ICheEntryService;
import com.ruoyi.mymod.service.IMessageService;
import com.ruoyi.mymod.service.IPhoneLoginService;
import com.ruoyi.mymod.utils.HttpClientUtil;
import com.ruoyi.mymod.utils.UserPerm;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.config.web.servlet.oauth2.login.UserInfoEndpointDsl;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 菜单 业务层处理
 *
 * @author ruoyi
 */
@Service
public class PhoneLoginServiceImpl implements IPhoneLoginService {

    private static final String APP_ID = "wxec1bce930447209f";
    private static final String APP_SECRET = "dc482d1d7c2503320a459469602f70eb";

    private static final String NTAPP_ID = "wx409682aa7a911b94";
    private static final String NTAPP_SECRET = "c068417b65a36b6440558a3aee829d0b";

    private static final String CHKAPP_ID = "wx993e55e338b3460a";
    private static final String CHKAPP_SECRET = "56a08b7a0239bd7aeba9f96077bfbaf8";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICheEntryService cheEntryService;

    public static final String PREMISSION_STRING = "perms[\"{0}\"]";


    public String phonelogin(String number) throws Exception {
        String url = "jdbc:oracle:thin:@10.104.8.7:1521:orcl"; // 使用服务名
        String user = "ctcnfd";
        String pd = "ctcnfd";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String name="查无此人";
        String ucode="0";
        String alevel="";
        String acode="";
        String tlevel="";
        String tcode="";
        String hasPig="";
        // 加载Oracle JDBC驱动

        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // 建立数据库连接
            conn = DriverManager.getConnection(url, user, pd);

            // 创建Statement对象
            stmt = conn.createStatement();

            // 执行SQL查询
            String sql = "select * from ai_user_feed_perm t where t.phone='"+number+"'";
            rs = stmt.executeQuery(sql);

            // 处理查询结果
            if (rs.next()){
                ucode=rs.getString(2);
                name=rs.getString(3);
                alevel=rs.getString(5);
                acode=rs.getString(6);
                tlevel=rs.getString(8);
                tcode=rs.getString(9);
                hasPig=rs.getString(12);
            }else {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
                throw new UserNotExistsException();

            }

        }finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }

        LoginUser loginUser1 = new LoginUser();
        loginUser1.setUserId((long)1);
        loginUser1.setDeptId((long)103);
        Set<String> permissions=new HashSet<>();
        permissions.add("*:*:*");
        loginUser1.setPermissions(permissions);
        SysUser sysUser = userService.selectUserById((long) 1);
        sysUser.setUserName(name);
        sysUser.setPhonenumber(number);
        sysUser.setSex(ucode+"/"+alevel+"/"+acode+"/"+tlevel+"/"+tcode);
        sysUser.setHasPig(hasPig);
        String userp = new UserPerm().getUserp(number);
        sysUser.setEmail(userp);
        loginUser1.setUser(sysUser);
        recordLoginInfo(loginUser1.getUserId());
        // 生成token
        return tokenService.createToken(loginUser1);
    }

    public String ntphonelogin(String number,String code) throws Exception {
        //通过code获取openid
        String url = "jdbc:oracle:thin:@10.104.8.7:1521:orcl"; // 使用服务名
        String user = "ctcnfd";
        String pd = "ctcnfd";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String name="查无此人";
        String userid="";
        String minpappid="";
        String minpName="";
        String minpUserid="";
        String permission="";
        String patrolPermission="";
        // 加载Oracle JDBC驱动

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

            // 建立数据库连接
            conn = DriverManager.getConnection(url, user, pd);

            // 创建Statement对象
            stmt = conn.createStatement();

            // 执行SQL查询
            String sql = "select * from WX_USER_MINP_USERID t where t.phone='"+number+"'";
            rs = stmt.executeQuery(sql);

            // 处理查询结果
            if (rs.next()){
                userid =rs.getString(1);
                name=rs.getString(2);
                minpappid=rs.getString(4);
                minpName=rs.getString(5);
                minpUserid=rs.getString(6);
                permission=rs.getString(7);
                patrolPermission=rs.getString(8);
            }else {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
                throw new UserNotExistsException();

            }

        }finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }

        LoginUser loginUser1 = new LoginUser();
        loginUser1.setUserId((long)1);
        loginUser1.setDeptId((long)103);
        Set<String> permissions=new HashSet<>();
        permissions.add("*:*:*");
        loginUser1.setPermissions(permissions);
        SysUser sysUser = userService.selectUserById((long) 1);
        sysUser.setUserName(name);
        sysUser.setPhonenumber(number);
        sysUser.setEmail(permission);
        sysUser.setHasPig(permission);
        sysUser.setPatrolPermission(patrolPermission);
        loginUser1.setUser(sysUser);
        recordLoginInfo(loginUser1.getUserId());
        // 生成token
        return tokenService.createToken(loginUser1);
    }

    public String chephonelogin(String number,String code) throws Exception {
        //通过code获取openid
        String url = "jdbc:oracle:thin:@10.104.8.7:1521:orcl"; // 使用服务名
        String user = "pigpos";
        String pd = "pigpos";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String name="查无此人";
        String userid="";
        String minpappid="";
        String minpName="";
        String minpUserid="";
        String permission="";
        String soppermission="";
        String patrolPermission="";
        String lv="";
        // 加载Oracle JDBC驱动

        try {

            Class.forName("oracle.jdbc.driver.OracleDriver");

            // 建立数据库连接
            conn = DriverManager.getConnection(url, user, pd);

            // 创建Statement对象
            stmt = conn.createStatement();

            // 执行SQL查询
            String sql = "select * from WX_USER t where t.phone='"+number+"'";
            rs = stmt.executeQuery(sql);

            // 处理查询结果
            if (rs.next()){
                userid =rs.getString(1);
                name=rs.getString(2);
                minpappid=rs.getString(4);
                minpName=rs.getString(5);
                minpUserid=rs.getString(6);
                lv=rs.getString(7);
                soppermission=rs.getString(8);
                patrolPermission=rs.getString(9);
            }else {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
                throw new UserNotExistsException();

            }

        }finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }

        LoginUser loginUser1 = new LoginUser();
        loginUser1.setUserId((long)1);
        loginUser1.setDeptId((long)103);
        Set<String> permissions=new HashSet<>();
        permissions.add("*:*:*");
        loginUser1.setPermissions(permissions);
        SysUser sysUser = userService.selectUserById((long) 1);
        sysUser.setUserName(name);
        sysUser.setPhonenumber(number);
        sysUser.setEmail(permission);
        sysUser.setHasPig(permission);
        sysUser.setPatrolPermission(patrolPermission);
        String piginfo = cheEntryService.getPiginfo(number);
        if (piginfo!=null && !"".equals(piginfo) && !"]".equals(piginfo)){
            sysUser.setHaspiginfo("Y");
        }else {
            sysUser.setHaspiginfo(null);
        }
        sysUser.setLv(lv);
        sysUser.setSoppermission(soppermission);
        loginUser1.setUser(sysUser);
        recordLoginInfo(loginUser1.getUserId());
        // 生成token
        return tokenService.createToken(loginUser1);
    }


    public Object getSessionKey(String code,String type) throws Exception {
        String tokenUrl="";
        if ("NT".equals(type)){
            tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", NTAPP_ID, NTAPP_SECRET);
        }else if ("YW".equals(type)){
            tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APP_ID, APP_SECRET);
        }else if ("CHE".equals(type)){
            tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", CHKAPP_ID, CHKAPP_SECRET);
        }
        String s = HttpUtil.get(tokenUrl);
        com.alibaba.fastjson2.JSONObject token = JSON.parseObject(s);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");
        //封装请求体
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);

        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

        //通过RestTemplate发送请求，获取到用户手机号码
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);




       // String tokenUrl1= String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", NTAPP_ID, NTAPP_SECRET,code);
        //String s1 = HttpUtil.get(tokenUrl1);
//        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
//        Map<String, String> requestUrlParam = new HashMap<>();
//        //小程序appId
//        requestUrlParam.put("appid", NTAPP_ID);
//        //小程序secret
//        requestUrlParam.put("secret",NTAPP_SECRET );
//        //小程序端返回的code
//        requestUrlParam.put("js_code", code);
//        //默认参数
//        requestUrlParam.put("grant_type", "authorization_code");
//        //发送post请求读取调用微信接口获取openid用户唯一标识
//        JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));


        //返回到前端展示
        return  response.getBody();

    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

}
